import { createRouter, createWebHistory } from "vue-router"
import type { RouteRecordRaw } from "vue-router"
import Login from "../views/login/index.vue"
import Layout from "../layout/index.vue"
import { getToken } from "../utils/utils"

const routes: RouteRecordRaw[] = [
  {
    path: "/",
    redirect: "/login",
  },
  {
    path: "/login",
    name: "Login",
    component: Login,
    meta: {
      title: "登录",
      requiresAuth: false,
    },
  },
  {
    path: "/",
    component: Layout,
    redirect: "/home",
    children: [
      {
        path: "home",
        name: "Home",
        component: () => import("../views/home/index.vue"),
        meta: {
          title: "控制台",
          requiresAuth: true,
        },
      },
      {
        path: "users",
        name: "Users",
        component: () => import("../views/users/index.vue"),
        meta: {
          title: "用户管理",
          requiresAuth: true,
        },
      },
      {
        path: "dept",
        name: "Dept",
        component: () => import("../views/dept/index.vue"),
        meta: {
          title: "部门管理",
          requiresAuth: true,
        },
      },
      {
        path: "facilitys/category",
        name: "Category",
        component: () => import("../views/facilitys/category/index.vue"),
        meta: {
          title: "设施分类管理",
          requiresAuth: true,
        },
      },
      {
        path: "facilitys/facility",
        name: "Facility",
        component: () => import("../views/facilitys/facility/index.vue"),
        meta: {
          title: "设施管理",
          requiresAuth: true,
        },
      },
      {
        path: "repair",
        name: "Repair",
        component: () => import("../views/repair/index.vue"),
        meta: {
          title: "工单管理",
          requiresAuth: true,
        },
      },
    ],
  },
  {
    path: "/:pathMatch(.*)*",
    component: Layout,
    children: [
      {
        path: "",
        name: "NotFound",
        component: () => import("../views/NotFound.vue"),
        meta: {
          title: "404",
          requiresAuth: false,
        },
      },
    ],
  },
]

const router = createRouter({
  history: createWebHistory(),
  routes,
})

// 全局前置守卫
router.beforeEach((to, from, next) => {
  // 设置页面标题
  document.title = `${to.meta.title} - 城市公共设施报修系统`

  // 判断该路由是否需要登录权限
  if (to.meta.requiresAuth) {
    const token = getToken()
    if (token) {
      next()
    } else {
      next({
        path: "/login",
        query: { redirect: to.fullPath },
      })
    }
  } else {
    next()
  }
})

export default router
